package com.loginTest;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


public class loginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化完成！");
    }

    @Override
    public void destroy() {
        System.out.println("项目结束！");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        //获取session对象,登录信息在其中
        HttpSession session = req.getSession();
        String username = (String) session.getAttribute("username");
        //获取cookie对象
        Cookie[] cookies = req.getCookies();
        //已经登录
        if(isSafe(req)){
            filterChain.doFilter(req,resp);
        }
        else{
            if(username != null){
                filterChain.doFilter(req,resp);
            }
            //没有登录
            else {
                boolean login = false;
                for(Cookie cookie : cookies){
                    login = "username".equals(cookie.getName());
                    //判断cookie中是否存在当前用户信息
                    if(login){
                        session.setAttribute("username",cookie.getValue());
                        filterChain.doFilter(req,resp);
                        break;
                    }
                }
                if(!login){
                    resp.sendRedirect("/");
                }
            }
        }
    }


    private boolean isSafe(HttpServletRequest req){
        String path = req.getRequestURI();
        if("/".equals(path) || "/login".equals(path)){
            return true;
        }
        return false;
    }
}
